package org.dromara.admin.controller;

import java.util.Arrays;
import java.util.List;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import org.dromara.admin.model.UserPasswordBo;
import org.dromara.admin.tenant.controller.TenantUserDetailController;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.file.MimeTypeUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.vo.SysOssUploadVo;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.admin.domain.vo.UserDetailVo;
import org.dromara.admin.domain.bo.UserDetailBo;
import org.dromara.admin.service.IUserDetailService;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 后台用户详细
 *
 * @author Lion Li
 * @date 2025-09-01
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/admin/userDetail")
public class AdminUserDetailController extends BaseController {

    private final IUserDetailService userDetailService;
    private final ISysOssService ossService;

    /**
     * 查询用户详细列表
     */
//    @SaCheckPermission("all:userDetail:list")
    @GetMapping("/list")
    public TableDataInfo<UserDetailVo> list(UserDetailBo bo, PageQuery pageQuery) {
        return userDetailService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询租户详细列表
     */
//    @SaCheckPermission("all:userDetail:list")
    @GetMapping("/tenantList")
    public TableDataInfo<UserDetailVo> tenantList(UserDetailBo bo, PageQuery pageQuery) {
        return userDetailService.queryPageTenantList(bo, pageQuery);
    }

    /**
     * 导出用户详细列表
     */
//    @SaCheckPermission("all:userDetail:export")
    @Log(title = "用户详细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(UserDetailBo bo, HttpServletResponse response) {
        List<UserDetailVo> list = userDetailService.queryList(bo);
        ExcelUtil.exportExcel(list, "用户详细", UserDetailVo.class, response);
    }

    /**
     * 获取用户详细详细信息
     *
     * @param userId 主键
     */
//    @SaCheckPermission("all:userDetail:query")
    @GetMapping("/{userId}")
    public R<UserDetailVo> getInfo(@NotNull(message = "主键不能为空")
                                   @PathVariable Long userId) {
        return R.ok(userDetailService.queryById(userId));
    }

    /**
     * 修改用户详细
     */
//    @SaCheckPermission("all:userDetail:edit")
    @Log(title = "用户详细", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody UserDetailBo bo) {
        return toAjax(userDetailService.updateByBo(bo));
    }

    /**
     * 后台管理员重置用户密码
     */
//    @SaCheckPermission("all:userDetail:resetPwd")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public R<Void> resetPwd(@RequestBody UserPasswordBo userPasswordBo) {
        if (StrUtil.isEmpty(userPasswordBo.getNewPassword())) {
            return R.fail("请输入密码！");
        }
        // 判断是否传递了userId
        if (userPasswordBo.getUserId() == null) {
            // 如果没有传递userId，则使用当前登录用户，修改当前登录用户的密码
            userPasswordBo.setUserId(LoginHelper.getUserId());
        }
        userPasswordBo.setNewPassword(BCrypt.hashpw(userPasswordBo.getNewPassword()));
        return toAjax(userDetailService.resetUserPwd(userPasswordBo.getUserId(), userPasswordBo.getNewPassword()));
    }

    /**
     * 删除用户详细
     *
     * @param userIds 主键串
     */
//    @SaCheckPermission("all:userDetail:remove")
    @Log(title = "用户详细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] userIds) {
        if (ArrayUtil.contains(userIds, LoginHelper.getUserId())) {
            return R.fail("当前用户不能删除");
        }
        return toAjax(userDetailService.deleteWithValidByIds(userIds, true));
    }

    /**
     * 后台头像上传
     *
     * @param avatarfile 用户头像
     */
//    @SaCheckPermission("all:userDetail:edit")
    @RepeatSubmit
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<TenantUserDetailController.AvatarVo> avatar(@RequestPart("avatarfile") MultipartFile avatarfile) {
        if (!avatarfile.isEmpty()) {
            String extension = FileUtil.extName(avatarfile.getOriginalFilename());
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return R.fail("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            SysOssVo oss = ossService.upload(avatarfile);
            Boolean updateSuccess = userDetailService.updateUserAvatar(LoginHelper.getUserId(), oss);
            String avatar = oss.getUrl();
            if (updateSuccess) {
                return R.ok(new TenantUserDetailController.AvatarVo(avatar));
            }
        }
        return R.fail("上传图片异常，请联系管理员");
    }

    /**
     * 上传OSS对象存储
     *
     * @param file 文件
     */
    @Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<SysOssUploadVo> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        SysOssVo oss = ossService.upload(file);
        SysOssUploadVo uploadVo = new SysOssUploadVo();
        uploadVo.setUrl(oss.getUrl());
        uploadVo.setFileName(oss.getOriginalName());
        uploadVo.setOssId(oss.getOssId().toString());
        return R.ok(uploadVo);
    }

    /**
     * 用户是否开启账本状态
     */
//    @SaCheckPermission("all:userDetail:enable")
    @Log(title = "用户详情", businessType = BusinessType.UPDATE)
    @PutMapping("/toggleStatus/{userId}")
    public R<Void> toggleAccountStatus(@NotNull(message = "用户ID不能为空") @PathVariable Long userId) {
        return toAjax(userDetailService.toggleAccountStatus(userId));
    }

    /**
     * 状态修改
     */
//    @SaCheckPermission("all:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus/{userId}")
    public R<Void> changeStatus(@NotNull(message = "用户ID不能为空") @PathVariable Long userId) {
        if (ObjectUtil.isNotNull(userId) && LoginHelper.isSuperAdmin(userId)) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
        return toAjax(userDetailService.updateUserStatus(userId));
    }

}
